<template>
  <div class="menu-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增菜单
          </el-button>
        </div>
      </template>

      <!-- 表格区域 -->
      <mobile-table
        :data="tableData"
        :current-page="1"
        :page-size="10"
        :total="tableData.length"
        :show-pagination="false"
        :tree-props="{ children: 'children' }"
        @toggle-expand="handleToggleExpand"
      >
        <!-- 桌面端表格 -->
        <template #desktop-table>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            row-key="id"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <el-table-column prop="name" label="菜单名称" />
            <el-table-column prop="icon" label="图标">
              <template #default="{ row }">
                <el-icon v-if="row.icon">
                  <component :is="row.icon" />
                </el-icon>
              </template>
            </el-table-column>
            <el-table-column prop="path" label="路径" />
            <el-table-column prop="component" label="组件" />
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-switch
                  v-model="row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleStatusChange(row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleEdit(row)">
                  编辑
                </el-button>
                <el-button type="success" size="small" @click="handleAddChild(row)">
                  新增
                </el-button>
                <el-button type="danger" size="small" @click="handleDelete(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>

        <!-- 移动端卡片 -->
        <template #mobile-card="{ row }">
          <div class="menu-card">
            <div class="menu-header">
              <div class="menu-info">
                <div class="menu-title">
                  <el-icon v-if="row.icon" class="menu-icon">
                    <component :is="row.icon" />
                  </el-icon>
                  <h3>{{ row.name }}</h3>
                </div>
                <p class="menu-path">{{ row.path }}</p>
              </div>
              <div class="menu-status">
                <el-switch
                  v-model="row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleStatusChange(row)"
                />
              </div>
            </div>

            <div class="menu-details">
              <div class="detail-item" v-if="row.component">
                <span class="label">组件：</span>
                <span class="value">{{ row.component }}</span>
              </div>
              <div class="detail-item">
                <span class="label">排序：</span>
                <span class="value">{{ row.sort }}</span>
              </div>
            </div>

            <div class="menu-actions">
              <el-button type="primary" size="default" @click="handleEdit(row)" class="action-btn">
                <el-icon><Edit /></el-icon>
                <span>编辑</span>
              </el-button>
              <el-button type="success" size="default" @click="handleAddChild(row)" class="action-btn">
                <el-icon><Plus /></el-icon>
                <span>新增</span>
              </el-button>
              <el-button type="danger" size="default" @click="handleDelete(row)" class="action-btn">
                <el-icon><Delete /></el-icon>
                <span>删除</span>
              </el-button>
            </div>
          </div>
        </template>
      </mobile-table>
    </el-card>

    <!-- 菜单表单对话框 -->
    <mobile-form
      v-model="dialogVisible"
      :title="dialogTitle"
      :loading="submitLoading"
      @confirm="handleSubmit"
      @close="handleDialogClose"
    >
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="menuRules"
        label-width="100px"
      >
        <el-form-item label="上级菜单" prop="parentId">
          <el-tree-select
            v-model="menuForm.parentId"
            :data="menuTreeData"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            placeholder="请选择上级菜单"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon">
          <el-input v-model="menuForm.icon" placeholder="请输入图标名称">
            <template #prepend>
              <el-icon v-if="menuForm.icon">
                <component :is="menuForm.icon" />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="路由路径" prop="path">
          <el-input v-model="menuForm.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="menuForm.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="menuForm.sort" :min="0" />
        </el-form-item>
        <el-form-item label="是否隐藏" prop="hidden">
          <el-switch v-model="menuForm.hidden" />
        </el-form-item>
      </el-form>
    </mobile-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Plus, Delete } from '@element-plus/icons-vue'
import MobileTable from '@/components/MobileTable/index.vue'
import MobileForm from '@/components/MobileForm/index.vue'

const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const menuFormRef = ref()

const menuForm = reactive({
  id: null,
  parentId: null,
  name: '',
  icon: '',
  path: '',
  component: '',
  sort: 0,
  hidden: false
})

const tableData = ref([])
const menuTreeData = ref([])

const dialogTitle = computed(() => {
  return menuForm.id ? '编辑菜单' : '新增菜单'
})

const menuRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入路由路径', trigger: 'blur' }
  ]
}

// 模拟菜单数据
const mockData = [
  {
    id: 1,
    name: '首页',
    icon: 'House',
    path: '/dashboard',
    component: 'dashboard/index',
    sort: 1,
    status: 1,
    parentId: null
  },
  {
    id: 2,
    name: '系统管理',
    icon: 'Setting',
    path: '/system',
    component: 'Layout',
    sort: 2,
    status: 1,
    parentId: null,
    children: [
      {
        id: 21,
        name: '用户管理',
        icon: 'User',
        path: '/system/user',
        component: 'system/user/index',
        sort: 1,
        status: 1,
        parentId: 2
      },
      {
        id: 22,
        name: '角色管理',
        icon: 'UserFilled',
        path: '/system/role',
        component: 'system/role/index',
        sort: 2,
        status: 1,
        parentId: 2
      },
      {
        id: 23,
        name: '菜单管理',
        icon: 'Menu',
        path: '/system/menu',
        component: 'system/menu/index',
        sort: 3,
        status: 1,
        parentId: 2
      }
    ]
  }
]

const fetchData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    tableData.value = mockData
    menuTreeData.value = [{ id: null, name: '顶级菜单', children: mockData }]
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleAddChild = (row) => {
  resetForm()
  menuForm.parentId = row.id
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(menuForm, row)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个菜单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    console.log('取消删除')
  }
}

const handleStatusChange = async (row) => {
  try {
    ElMessage.success(`菜单状态已${row.status ? '启用' : '禁用'}`)
  } catch (error) {
    ElMessage.error('状态切换失败')
    row.status = row.status ? 0 : 1
  }
}

const handleToggleExpand = (row, expanded) => {
  console.log('树形节点展开状态变化:', row.name, expanded)
  // 这里可以添加展开状态的处理逻辑
  // 比如记录展开状态、懒加载子节点等
}

const handleSubmit = async () => {
  if (!menuFormRef.value) return
  
  try {
    const valid = await menuFormRef.value.validate()
    if (!valid) return
    
    submitLoading.value = true
    
    // 模拟提交
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(menuForm.id ? '更新成功' : '创建成功')
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  menuForm.id = null
  menuForm.parentId = null
  menuForm.name = ''
  menuForm.icon = ''
  menuForm.path = ''
  menuForm.component = ''
  menuForm.sort = 0
  menuForm.hidden = false
  if (menuFormRef.value) {
    menuFormRef.value.clearValidate()
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.menu-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 移动端卡片样式 */
.menu-card {
  .menu-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;

    .menu-info {
      flex: 1;

      .menu-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 4px;

        .menu-icon {
          color: #409EFF;
          font-size: 16px;
        }

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #333;
        }
      }

      .menu-path {
        margin: 0;
        font-size: 14px;
        color: #666;
        font-family: monospace;
        background: #f5f5f5;
        padding: 2px 6px;
        border-radius: 3px;
        display: inline-block;
      }
    }

    .menu-status {
      display: flex;
      align-items: center;
    }
  }

  .menu-details {
    margin-bottom: 12px;

    .detail-item {
      display: flex;
      margin-bottom: 6px;
      font-size: 14px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        color: #666;
        min-width: 60px;
      }

      .value {
        color: #333;
        flex: 1;
        word-break: break-all;
      }
    }
  }

  .menu-actions {
    display: flex;
    gap: 8px;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;
    flex-wrap: wrap;

    .el-button {
      flex: 1;
      min-width: 80px;
    }
  }
}

// 菜单卡片样式
.menu-card {
  width: 100%;
  padding: 0;
  margin: 0;

  .menu-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16px;

    .menu-info {
      flex: 1;

      .menu-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 4px;

        .menu-icon {
          font-size: 18px;
          color: #007AFF;
        }

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #1d1d1f;
        }
      }

      .menu-path {
        margin: 0;
        font-size: 14px;
        color: #8e8e93;
      }
    }

    .menu-status {
      flex-shrink: 0;
    }
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .menu-container {
    padding: 10px;
  }

  // 全局重置，确保所有层级的按钮都对齐
  :deep(.tree-item) {
    .content-section {
      .menu-card {
        .menu-actions {
          margin-left: 0 !important;
          margin-right: 0 !important;
          padding-left: 0 !important;
          padding-right: 0 !important;

          .action-btn {
            width: 100% !important;
            margin: 0 !important;
          }
        }
      }
    }
  }

  .card-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;

    .el-button {
      width: 100%;
    }
  }

  // 移动端按钮优化
  .menu-actions {
    display: grid;
    grid-template-columns: 1fr;
    gap: 12px;
    margin-top: 16px;
    // 确保按钮在所有层级都对齐
    margin-left: 0 !important;
    margin-right: 0 !important;
    padding: 0;
    width: 100%;

    .action-btn {
      width: 100%;
      height: 48px;
      border-radius: 12px;
      font-size: 16px;
      font-weight: 500;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      // 重置任何可能的边距和内边距
      margin: 0 !important;
      padding: 0 16px;
      box-sizing: border-box;

      .el-icon {
        font-size: 18px;
      }

      span {
        font-size: 16px;
      }

      // 按钮颜色优化
      &.el-button--primary {
        background: linear-gradient(135deg, #007AFF 0%, #0056CC 100%);
        border: none;
        box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);

        &:hover {
          background: linear-gradient(135deg, #0056CC 0%, #003D99 100%);
          box-shadow: 0 4px 12px rgba(0, 122, 255, 0.4);
          transform: translateY(-1px);
        }
      }

      &.el-button--success {
        background: linear-gradient(135deg, #34C759 0%, #28A745 100%);
        border: none;
        box-shadow: 0 2px 8px rgba(52, 199, 89, 0.3);

        &:hover {
          background: linear-gradient(135deg, #28A745 0%, #1E7E34 100%);
          box-shadow: 0 4px 12px rgba(52, 199, 89, 0.4);
          transform: translateY(-1px);
        }
      }

      &.el-button--danger {
        background: linear-gradient(135deg, #FF3B30 0%, #DC3545 100%);
        border: none;
        box-shadow: 0 2px 8px rgba(255, 59, 48, 0.3);

        &:hover {
          background: linear-gradient(135deg, #DC3545 0%, #C82333 100%);
          box-shadow: 0 4px 12px rgba(255, 59, 48, 0.4);
          transform: translateY(-1px);
        }
      }

      &:active {
        transform: translateY(0) scale(0.98);
      }
    }
  }
}
</style>
